<?php
namespace Modules\Home\Services;

use Common\Models\UserModel;
use Common\Models\UserAchievementModel;

class UserAchievementService {
  public function getOne($user_id) {
    $findFirstUserAchievement = UserAchievementModel::findFirst($user_id);
    if(!$findFirstUserAchievement) {
      return $this -> create([
        'user_id' => $user_id,
        'month_amount_left' => 0,
        'month_amount_right' => 0,
        'day_amount_left' => 0,
        'day_amount_right' => 0
      ]);
    }

    return ['code' => 0, 'user_achievement' => $findFirstUserAchievement];
  }

  /**
   * 业绩增加
   */
  public function addUserAchievement($user_id) {
    $findFirstUser = UserModel::findFirst('user_id = ' . $user_id);
    if(!$findFirstUser) {
      return ['code' => -1, 'message' => '用户不存在!'];
    }

    $treeIndexs = '';
    $currentTreeIndex = $findFirstUser -> tree_index;
    while(true) {
      $treeIndexs .= $currentTreeIndex . ',';
      if($currentTreeIndex <= 1) {
        break;
      }
      $currentTreeIndex = intval($currentTreeIndex / 2);
    }

    $findUser = UserModel::find([
      'conditions' => 'tree_top_id = ' . $findFirstUser -> tree_top_id . ' AND tree_index in (' . rtrim($treeIndexs, ',') . ')',
      'columns' => 'user_id, node_side',
      'order' => 'user_id DESC'
    ]);

    $userIds = '';
    $userArray = [];
    foreach($findUser as $user) {
      $userIds .= $user -> user_id . ',';
      $userArray[$user -> user_id] = $user;
    }
    $userIds = rtrim($userIds, ',');

    $findUserAchievement = UserAchievementModel::find('user_id in (' . $userIds . ')');
    $userAchievementArray = [];
    foreach($findUserAchievement as $userAchievement) {
      $userAchievementArray[$userAchievement -> user_id] = $userAchievement;
    }

    if(count($userArray) != $findUserAchievement -> count()) {
      foreach($userArray as $user) {
        if(!isset($userAchievementArray[$user -> user_id])) {
          $createUserAchievement = $this -> create([
            'user_id' => $user -> user_id,
            'month_amount_left' => 0,
            'month_amount_right' => 0,
            'day_amount_left' => 0,
            'day_amount_right' => 0
          ]);
          if($createUserAchievement['code'] != 0) {
            continue;
          }
          $userAchievementArray[$user -> user_id] = $createUserAchievement['user_achievement'];
        }
      }
    }

    foreach($userAchievementArray as $userAchievement) {
      $userAchievementLogData = [];
      switch($userArray[$userAchievement -> user_id] -> node_side) {
        case '1':
          $userAchievement -> month_amount_left += 1500;
          $userAchievement -> day_amount_left += 1500;
          $userAchievementLogData['amount_left'] = 1500;
          break;
        case '2':
          $userAchievement -> month_amount_right += 1500;
          $userAchievement -> day_amount_right += 1500;
          $userAchievementLogData['amount_right'] = 1500;
          break;
        default:
          $secondUserArray = array_slice($userArray, -2, 1);

          switch($secondUserArray[0] -> node_side) {
            case '1':
              $userAchievement -> month_amount_left += 1500;
              $userAchievement -> day_amount_left += 1500;
              $userAchievementLogData['amount_left'] = 1500;
              break;
            case '2':
              $userAchievement -> month_amount_right += 1500;
              $userAchievement -> day_amount_right += 1500;
              $userAchievementLogData['amount_right'] = 1500;
              break;
          }
      }

      $currentTime = time();
      if($userAchievement -> update()) {
        // 创建业绩记录
        $userAchievementLogData['user_id'] = $userAchievement -> user_id;
        $userAchievementLogData['from_user_id'] = $user_id;
        $userAchievementLogData['type'] = 1;
        $userAchievementLogData['create_time'] = $currentTime;
        $createUserAchievementLog = (new UserAchievementLogService()) -> create($userAchievementLogData);
      }
    }

    return ['code' => 0, 'message' => 'Success!'];
  }

  public function create($data) {
    $userAchievementModel = new UserAchievementModel($data);
    try {
      if(!$userAchievementModel -> create()) {
        $messages = $userAchievementModel -> getMessages();
        throw new \Exception($messages[0] -> getMessage());
      }
    } catch(\Exception $e) {
      return ['code' => -1, 'message' => $e -> getMessage()];
    }

    return ['code' => 0, 'user_achievement' => $userAchievementModel];
  }
}
?>